// pages/goods/detail/goodsdetail.js
var request = require('../../../utils/request.js')
var config = require('../../../config.js');
var appkey = require('../../../appkey.js');
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    productPrice:0, //规格价格
    goodsInfo: {},
    goodsSlide: [],
    goodsAttrs: [],
    goodsDesc: [],
    goodsProducts: [],
    showModalStatus: false,
    animationData: null,
    optionBtnValue: '购买',
    optionBtnType: 'buy',
    goodsNum: 1,//购物数量
    goodsId: 0,
    selectStandard: {},//选中规格
    productMax: 1,//选中规格最大库存
    selectProduct: undefined,//选中商品
    isIpx: app.globalData.isIpx,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      goodsId: options.id,
    });
    this.getGoodsDetailAction();
  },
 

  /**
   * 加入购物车
   */
  addCarDialog: function () {
    this.setData({
      optionBtnType: 'add_car',
      optionBtnValue: '加入购物车'
    });
    this.showModal();
  },

  /**
   * 立即购买
   */
  payGoodsDialog: function () {
    this.setData({
      optionBtnType: 'pay',
      optionBtnValue: '购买'
    });
    this.showModal();
  },


  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 100)
  },


  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 100)
  },


  minusCount: function (e) {
    var count = this.data.goodsNum;
    if (count > 1) {
      count = count - 1;
      this.setData({
        goodsNum: count
      })
    }
  },

  addCount: function (e) {
    var count = this.data.goodsNum;
    count = count + 1;
    this.setData({
      goodsNum: count
    })

  },

  changenumAction: function (e) {
    var count = parseInt(e.detail.value);
    this.setData({
      goodsNum: count
    })
  },

  /**
   * 获取商品详情
   */
  getGoodsDetailAction: function () {
    var params = {
      id: this.data.goodsId
    }
    var self = this;
    var url = config.goodsDetailUrl;
    request.requestPost(url, params)
      .then(data => {
        console.log(data);
        var slide = data.goods.goods_slider;
        var slides = slide.split(';');
        self.setData({
          goodsInfo: data.goods,
          productPrice: parseFloat(data.goods.shop_price/100).toFixed(2), //规格商品价格
          goodsSlide: slides,
          goodsDesc: JSON.parse(data.goods.goods_desc),
          goodsProducts: data.products
        });

        //处理属性 attr_value 数据
        var attrs = [];
        var goodsAttr = {};
        var attr = [];
        var standard = {};
        data.goodsAttrs.map(item => {
          goodsAttr = item;
          attr = item.attr_value.split(';');
          goodsAttr.attr_value = attr;
          if (item.attr_value != ""){
            attrs.push(goodsAttr);
          }
          if (item.is_normal == 0) {
            standard[item.goods_attr_id] = '';
          }
        });

        self.setData({
          goodsAttrs: attrs,
          selectStandard: standard
        });

      }).catch(msg => {
        console.log(msg);
      })
  },


  chooseAttrAction: function (event) {
    var index = event.currentTarget.dataset.index;
    var sub = event.currentTarget.dataset.sub;
    var attrid = this.data.goodsAttrs[index].goods_attr_id;
    var standard = this.data.selectStandard;
    standard[attrid] = this.data.goodsAttrs[index].attr_value[sub];
    this.setData({
      selectStandard: standard
    });

    //计算规格的库存数目
    var selectValues = [];
    for (var k in standard) {
      selectValues.push(standard[k])
    }

    this.data.goodsProducts.map(item => {
      if (item.goods_attr == selectValues.join(';')) {
        console.log(item);
        this.setData({
          selectProduct: item,
          productPrice: parseFloat(item.product_shop_price / 100).toFixed(2)
        })
      }
    });
  },


  buyAction: function () {
    var type = this.data.optionBtnType;
    if (type == 'add_car') {
      this.addCarAction();
    } else {
      this.payAction();
    }
  },



  /**
   * 加入购物车
   * token	用户token	否
   * shoppingKey	购物车key	否	第一次加入购物车时可为空
   * productId	产品id	是
   * count	数量
   */
  addCarAction: function () {
    var url = config.addCarUrl;
    var token = wx.getStorageSync('token');
    var spk = wx.getStorageSync(appkey.shoppingkey);
    var count = this.data.goodsNum;
    var id = '';
    if (this.data.selectProduct != undefined){
       id = this.data.selectProduct.product_id;
    }else{
      wx.showToast({
        title: '请选择规格',
        icon:'none'
      });
      return;
    }
   
    var self = this;
    var params = {
      token: token,
      shoppingKey: spk,
      productId: id,
      count: count
    }
    console.log(params);
    request.requestPost(url, params)
      .then(data => {
        wx.showToast({
          title: '添加成功',
        });
        if (data.shoppingKey){
          wx.setStorageSync('shopkey', data.shoppingKey)
        };
        self.hideModal();
        console.log(data);
      }).catch(msg => {
        console.log('加入失败' + msg)
      })
  },

  /**
   * 购买
   */
  payAction: function () {

  },


  /**
   * 去购物车
   */
  goToCar: function () {
    wx.switchTab({
      url: '../../cart/cart',
    })
  },

})